package com.wise.gemmes.controller.equipment;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSRole;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import com.fr.base.core.RSADecode;
import com.wise.gemmes.entity.equipment.Gem_equip_typeEntity;
import com.wise.gemmes.entity.equipment.Gem_manu_equipmentEntity;
import com.wise.gemmes.service.equipment.Gem_manu_equipmentServiceI;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;

/**   
 * @Title: Controller
 * @Description: 设备表
 * @author zhangdaihao
 * @date 2018-03-14 09:10:14
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/gem_manu_equipmentController")
public class Gem_manu_equipmentController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(Gem_manu_equipmentController.class);

	@Autowired
	private Gem_manu_equipmentServiceI gem_manu_equipmentService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 设备表列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/wise/gemmes/equipment/gem_manu_equipmentList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(Gem_manu_equipmentEntity gem_manu_equipment,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(Gem_manu_equipmentEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, gem_manu_equipment, request.getParameterMap());
		this.gem_manu_equipmentService.getDataGridReturn(cq, true);
		
		List<Gem_manu_equipmentEntity> list = dataGrid.getResults();
		Map<String,Map<String,Object>> map = new  HashMap<String,Map<String,Object>>(); 
		for(Gem_manu_equipmentEntity model : list){
			Map<String,Object> m=new HashMap<String,Object>();
			String hql=" from Gem_equip_typeEntity where id='"+model.getTypes()+"'";
			List<Gem_equip_typeEntity> modellist=this.systemService.findByQueryString(hql);
			if(modellist.size()>0){
				for (Gem_equip_typeEntity Gem_equip_typeEntity : modellist) {
					m.put("typename",Gem_equip_typeEntity.getName());
					map.put(model.getId(),m);		  
				}	
			}
		}
		System.out.println(cq.toString());
		TagUtil.datagrid(response,dataGrid,map);
	}

	/**
	 * 删除设备表
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(Gem_manu_equipmentEntity gem_manu_equipment, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		gem_manu_equipment = systemService.getEntity(Gem_manu_equipmentEntity.class, gem_manu_equipment.getId());
		message = "设备表删除成功";
		gem_manu_equipmentService.delete(gem_manu_equipment);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加设备表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(Gem_manu_equipmentEntity gem_manu_equipment, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		if (StringUtil.isNotEmpty(gem_manu_equipment.getId())) {
			message = "设备表更新成功";
			Gem_manu_equipmentEntity t = gem_manu_equipmentService.get(Gem_manu_equipmentEntity.class, gem_manu_equipment.getId());
			try {
				MyBeanUtils.copyBeanNotNull2Bean(gem_manu_equipment, t);
				gem_manu_equipmentService.saveOrUpdate(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
			} catch (Exception e) {
				e.printStackTrace();
				message = "设备表更新失败";
			}
		} else {
			message = "设备表添加成功";
			gem_manu_equipmentService.save(gem_manu_equipment);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 设备表列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(Gem_manu_equipmentEntity gem_manu_equipment, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(gem_manu_equipment.getId())) {
			gem_manu_equipment = gem_manu_equipmentService.getEntity(Gem_manu_equipmentEntity.class, gem_manu_equipment.getId());
			req.setAttribute("gem_manu_equipmentPage", gem_manu_equipment);
		}
		return new ModelAndView("com/wise/gemmes/equipment/gem_manu_equipment");
	}
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<Gem_manu_equipmentEntity> list() {
		List<Gem_manu_equipmentEntity> listGem_manu_equipments=gem_manu_equipmentService.getList(Gem_manu_equipmentEntity.class);
		return listGem_manu_equipments;
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<?> get(@PathVariable("id") String id) {
		Gem_manu_equipmentEntity task = gem_manu_equipmentService.get(Gem_manu_equipmentEntity.class, id);
		if (task == null) {
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
		return new ResponseEntity(task, HttpStatus.OK);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResponseEntity<?> create(@RequestBody Gem_manu_equipmentEntity gem_manu_equipment, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<Gem_manu_equipmentEntity>> failures = validator.validate(gem_manu_equipment);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		gem_manu_equipmentService.save(gem_manu_equipment);

		//按照Restful风格约定，创建指向新任务的url, 也可以直接返回id或对象.
		String id = gem_manu_equipment.getId();
		URI uri = uriBuilder.path("/rest/gem_manu_equipmentController/" + id).build().toUri();
		HttpHeaders headers = new HttpHeaders();
		headers.setLocation(uri);

		return new ResponseEntity(headers, HttpStatus.CREATED);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<?> update(@RequestBody Gem_manu_equipmentEntity gem_manu_equipment) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<Gem_manu_equipmentEntity>> failures = validator.validate(gem_manu_equipment);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		gem_manu_equipmentService.saveOrUpdate(gem_manu_equipment);

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return new ResponseEntity(HttpStatus.NO_CONTENT);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	public void delete(@PathVariable("id") String id) {
		gem_manu_equipmentService.deleteEntityById(Gem_manu_equipmentEntity.class, id);
	}
	//add
	/**
	 * 设备表列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "equiplist")
	public ModelAndView equiplist(HttpServletRequest request) {
		String typeId = request.getParameter("type_id");
		request.setAttribute("type_id", typeId);
		return new ModelAndView("com/wise/gemmes/equipment/gem_equip_model_List");
	}

	@RequestMapping(params = "equipdatagrid")
	public void equipdatagrid(Gem_manu_equipmentEntity gem_manu_equipment,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(Gem_manu_equipmentEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, gem_manu_equipment, request.getParameterMap());
		this.gem_manu_equipmentService.getDataGridReturn(cq, true);
		String typeId = request.getParameter("type_id");
		try{
			if(typeId != null){
			  cq.eq("types", typeId);
			}
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.systemService.getDataGridReturn(cq, true);
		
		List<Gem_manu_equipmentEntity> list = dataGrid.getResults();
		Map<String,Map<String,Object>> map = new  HashMap<String,Map<String,Object>>(); 
		for(Gem_manu_equipmentEntity model : list){
			Map<String,Object> m=new HashMap<String,Object>();
			String hql=" from Gem_equip_typeEntity where id='"+model.getTypes()+"'";
			List<Gem_equip_typeEntity> modellist=this.systemService.findByQueryString(hql);
			if(modellist.size()>0){
				for (Gem_equip_typeEntity Gem_equip_typeEntity : modellist) {
					m.put("typename",Gem_equip_typeEntity.getName());
					map.put(model.getId(),m);		  
				}	
			}
		}
		TagUtil.datagrid(response, dataGrid,map);
	}
	//添加可替换设备
	@RequestMapping(params = "Add")
	public ModelAndView View(HttpServletRequest rq){
		System.out.println(rq.getParameter("id").toString());
		//model.addAttribute("typemid", rq.getParameter("id"));
		//rq.setAttribute("type_id", rq.getParameter("id"));
		ModelAndView md = new ModelAndView("com/wise/gemmes/equipment/gem_manu_equipment");
		md.addObject("typemid", rq.getParameter("id"));
		return md;
	}
	
}
